package com.neusoft.SPNursingHome.common;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neusoft.SPNursingHome.dao.AdminDao;
import com.neusoft.SPNursingHome.po.UserSession;
import com.neusoft.SPNursingHome.redisDao.RedisDao;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.*;

@Component
public class TokenAuthFilter extends OncePerRequestFilter {

    private final RedisDao redisDao;
    private final AdminDao adminDao;
    private final ObjectMapper objectMapper = new ObjectMapper();

    private static final Map<String,String> ROLE_MAP = Map.of(
            "管理员",   "ADMIN",
            "健康管家","CARE_WORKER"
    );

    public TokenAuthFilter(RedisDao redisDao, AdminDao adminDao) {
        this.redisDao = redisDao;
        this.adminDao = adminDao;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest req,
                                    HttpServletResponse resp,
                                    FilterChain chain)
            throws ServletException, IOException {

        String token = req.getHeader("token");
        if (StringUtils.hasText(token)) {
            String raw = redisDao.get("token:" + token);
            if (raw != null) {
                Integer adminId;
                String adminName;
                String mappedRole;

                if (raw.matches("\\d+")) {
                    // 兼容老逻辑
                    adminId = Integer.valueOf(raw);
                    var admin = adminDao.selectById(adminId);
                    adminName = admin.getAdName();
                    mappedRole = ROLE_MAP.getOrDefault(admin.getRole(), admin.getRole());
                } else {
                    // 读取 JSON
                    Map<String,Object> session = objectMapper.readValue(
                            raw, new TypeReference<Map<String,Object>>(){}
                    );
                    adminId   = (Integer) session.get("adminId");
                    adminName = (String) session.get("adminName");
                    mappedRole= (String) session.get("role");
                }

                // 构造 UserSession，设置到 SecurityContext
                UserSession us = new UserSession(adminId, adminName, mappedRole);
                var authority = new SimpleGrantedAuthority("ROLE_" + mappedRole);
                var auth = new UsernamePasswordAuthenticationToken(
                        us, null, List.of(authority));
                SecurityContextHolder.getContext().setAuthentication(auth);
            }
        }
        chain.doFilter(req, resp);
    }
}
